package snafu.implementation.actions.drop.random;

import java.util.List;
import java.util.Set;

import snafu.framework.actions.AbstractAction;
import snafu.framework.actions.Intention;
import snafu.framework.objects.WorldObject;
import snafu.framework.states.StateItself;
import snafu.framework.view.Access;
import snafu.framework.worlds.Position;
import snafu.framework.worlds.Tile;
import snafu.framework.worlds.WorldMap;
import snafu.implementation.states.literals.have.HaveLiteral;
import snafu.implementation.states.literals.position.PositionLiteral;
import snafu.implementation.states.literals.position.PositionLiteralItself;

public class RandomDropAction extends AbstractAction {
	public RandomDropAction(List<WorldObject> target, Intention<?> intention) {
		super(target, intention);
	}

	@Override
	public void execute(WorldMap worldMap) {
		WorldObject target = targets.get(0);
		
		// get state
		StateItself agentState = (StateItself) agent.getState();
		StateItself targetState = (StateItself) target.getState();

		// get haveliteral for target
		HaveLiteral haveLiteral = null;
		List<HaveLiteral> literals = agentState.getLiterals(HaveLiteral.class);
		for (HaveLiteral literal : literals) {
			if (literal.getValue().equals(target)) {
				haveLiteral = literal;
				break;
			}
		}

		// get random target position from neighborhood
		Position position = agentState.getLiteral(PositionLiteral.class);
		Set<Tile> neighborhood = worldMap.getNeighborhood(position);
		
		boolean toFind = true;
		while (toFind) {
			int index = (int) (Math.random() * neighborhood.size());
			position = neighborhood.toArray(new Tile[0])[index].getPosition();
			toFind = position == null;
		}
		
		// add target to map
		worldMap.addObject(position, target);
		// remove target from agent
		agentState.removeLiteral(haveLiteral);
		// set current target position
		targetState.setLiteral(new PositionLiteralItself(position, Access.PRIVATE));
	}

	@Override
	public String output() {
		return null;
	}

	@Override
	public boolean supportMultiTargets() {
		return false;
	}
}
